#include "uicontrol.h"
#include <QMessageBox>
#include <QFileDialog>
#include "../QClient/QClientInterface.h"
#include "../QClient/Discover.h"
#include "startupdialog.h"
#include "lanqwindow.h"

static LanqWindow *lanqWindow;
UIControl UIControl::instance = UIControl();
int _argc;
char **_argv;

UIControl::UIControl()
{
    lanqInit = false;
}

UIControl::~UIControl()
{
}

string UIControl::ask_for_save(User &counterpart, string &filename)
{
    QString q_filename = QString::fromStdString(filename);
    QString msg = QString::fromStdString(counterpart.name);
    msg.append("(");
    msg.append(QString::fromStdString(counterpart.ip));
    msg.append(") wants to send you a file named ");
    msg.append(q_filename);
    msg.append(".\nWould you like to save it or not?");
    int flag = QMessageBox::information(NULL, "Save or not?", msg,"save","cancel");
    switch(flag)
    {
        case 0 :{
            QString path = QFileDialog::getExistingDirectory(NULL,"Select a directory","/home",QFileDialog::ShowDirsOnly);
            // TODO save file
            string str = path.toStdString();
            return str;
        }
        case 1:{
            // TODO cancel save
            return "";
        }
        default:{
            // TODO cancel save
            return "";
        }
    }
}

UIControl& UIControl::getInstance()
{
    return instance;
}

void UIControl::startup_ui()
{
    StartupDialog welcomeDialog;
    welcomeDialog.show();
}

void UIControl::show_lanq_window(User &myInfo)
{
    lanqWindow = new LanqWindow(myInfo);
    lanqWindow->show();
    pthread_t tid;
    pthread_create(&tid,NULL,thread_update,NULL);
}

void UIControl::new_msg_in(User &counterpart, string& msg)
{
    lanqWindow->counterPartSay(counterpart,msg);
}

void UIControl::update_list(vector<User> &list)
{
    lanqWindow->updateUserList(list);
}

void* UIControl::thread_update(void* arg)
{
    vector<User> list ;
    while(true){
        list = getOnlineUsers();
        UIControl::getInstance().update_list(list);
        for(int i = 0; i < list.size();i++){
            User u = list[i];
            cout << "name:" << u.name << endl;
        }
        sleep(RETRIEVE_INTERVAL);
    }
}

void UIControl::set_lanq_window(void* w)
{
    lanqWindow = (LanqWindow*)w;
    pthread_t tid;
    pthread_create(&tid,NULL,thread_update,NULL);
}
